/**
 * @Title: SystemUtil.java
 * @Package com.uroad.com.uroad.locmap.util
 * @Description: TODO(��һ�仰������ļ���ʲô)
 * @author oupy
 * @date 2013-9-23 ����2:32:36
 * @version V1.0
 */
package com.uroad.lib.util.sys;

import android.app.Activity;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.location.LocationManager;
import android.net.Uri;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.uroad.lib.util.string.StringUtils;

/**
 * 系统操作工具类
 */
public class SystemUtil {

    /**
     * 关闭软键盘
     *
     * @param obj
     * @return
     */
    public static void closeSoftKeyboard(Context c, EditText et) {
        try {
            InputMethodManager inputManager = (InputMethodManager) c
                    .getSystemService(Context.INPUT_METHOD_SERVICE);

            inputManager.hideSoftInputFromWindow(et.getWindowToken(), 0);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

    /**
     * 打开软键盘
     *
     * @param obj
     * @return
     */
    public static void openSoftKeyboard(Context c, EditText et) {
        try {
            et.requestFocus();
            InputMethodManager inputManager = (InputMethodManager) c
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

    /**
     * 获取设备deviceid
     *
     * @param obj
     * @return
     */
    public static String getDeviceId(Context context) {
        TelephonyManager telephonyManager = ((TelephonyManager) context
                .getSystemService(context.TELEPHONY_SERVICE));
        return telephonyManager.getDeviceId();
    }

    /**
     * 清除app缓存(仅sharedprference)
     */
    public static void clearAppCacheOfSp(Context context, String spname) {
        SharedPreferences preferences = context.getSharedPreferences(spname,
                Activity.MODE_PRIVATE);
        if (preferences != null) {
            Editor editor = preferences.edit();
            editor.clear();
            editor.commit();
        }
    }

    /**
     * 打电话(直接拨打电话)
     *
     * @param c
     * @param tel
     */
    public static void CallPhone(Context c, String tel) {
        try {
            Uri phoneNumber = Uri.parse("tel:" + tel);
            Intent call = new Intent(Intent.ACTION_CALL, phoneNumber);
            c.startActivity(call);
        } catch (Exception e) {
            Toast.makeText(c, "改设备不支持电话功能", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 打电话（跳转到打电话界面）
     *
     * @param c
     * @param tel
     */
    public static void CallPhone2(Context c, String tel) {
        try {
            Uri phoneNumber = Uri.parse("tel:" + tel);
            Intent call = new Intent(Intent.ACTION_DIAL, phoneNumber);
            c.startActivity(call);
        } catch (Exception e) {
        }
    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     *
     * @param context
     * @return true 表示开启
     */
    public static final boolean isGPSOPen(final Context context) {
        LocationManager locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        // boolean network =
        // locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps) {
            return true;
        }
        return false;
    }

    public static final boolean isNetworkLocationOPen(final Context context) {
        LocationManager locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);

        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (network) {
            return true;
        }

        return false;
    }

    /**
     * 强制帮用户打开GPS
     *
     * @param context
     */
    public static final void openGPS(Context context) {
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
        } catch (CanceledException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打开蓝牙
     *
     * @param askuser 是否询问用户
     */
    public static final void OpenBlue(boolean askuser, Context ct) {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (null == adapter) {
            return;
        } else {
            if (!adapter.isEnabled()) {
                if (askuser) {
                    // 询问用户
                    Intent intent = new Intent(
                            BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    // 设置蓝牙可见性，最多300秒
                    intent.putExtra(
                            BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
                    ct.startActivity(intent);
                } else {
                    adapter.enable();
                }

            }

        }
    }

    public static final void CloseBlue() {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (null == adapter) {
            return;
        } else {
            if (adapter.isEnabled()) {
                adapter.disable();
            }
        }
    }

    /***
     * 获取屏幕宽度
     *
     * @param activity
     * @return
     */
    public static int getScreenWidth(Activity activity) {
        DisplayMetrics metric = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
        return metric.widthPixels;
    }

    /***
     * 获取屏幕高度
     *
     * @param activity
     * @return
     */
    public static int getScreenHeight(Activity activity) {
        DisplayMetrics metric = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
        return metric.heightPixels;
    }

    /**
     * dip 转成 px
     *
     * @param context
     * @param dpValue
     * @return
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * px 转成 dip
     *
     * @param context
     * @param pxValue
     * @return
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 获取颜色选择器
     */
    public static ColorStateList getColorStateList(Context context, int resId) {
        return context.getResources().getColorStateList(resId);
    }

    /**
     * 获取系统版本名
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);
            return pi.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取系统版本号
     *
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);
            return pi.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
    /**
     * 检查当前版本是否小于最新版本 if(currVerson < lastVerson) return true;
     * currVerson APP当前版本       1.6.1
     * lastVerson 接口返回的最新版本 1.7.8
     * */
    public static boolean isNeedUpdate(String currVerson,String lastVerson){
        try{
            boolean result = false;
            String[] currVerson_array = currVerson.split("\\.");
            String[] lastVerson_array = lastVerson.split("\\.");
            if(currVerson_array.length == 2){
                if (currVerson_array[1].length() == 2) {
                    currVerson_array = new String[]{currVerson_array[0],
                            currVerson_array[1].substring(0, 1), currVerson_array[1].substring(1)};
                }else {
                    currVerson_array = new String[]{currVerson_array[0], currVerson_array[1], "0"};
                }
            }
            if(lastVerson_array.length == 2){
                if (lastVerson_array[1].length() == 2) {
                    lastVerson_array = new String[]{lastVerson_array[0],
                            lastVerson_array[1].substring(0, 1), lastVerson_array[1].substring(1)};
                }else {
                    lastVerson_array = new String[]{lastVerson_array[0], lastVerson_array[1], "0"};
                }
            }
            if(currVerson_array.length == 3 && lastVerson_array.length == 3){
                for(int i = 0;i<3;i++){
                    long curr = StringUtils.Convert2Long(currVerson_array[i]);
                    long last = StringUtils.Convert2Long(lastVerson_array[i]);
                    if(curr < last){
                        return true;
                    }else if(curr == last){
                        continue;
                    }else{
                        return false;
                    }
                }
            }else{
                //数据格式异常，则视为不需要更新
                return false;
            }
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }

    }
}
